//
//  CCSubTagController.m
//  BuDeJie
//
//  Created by demoncraz on 2017/2/11.
//  Copyright © 2017年 demoncraz. All rights reserved.
//

#import "CCSubTagController.h"
#import "CCSubTagCell.h"
#import "CCSubTagItem.h"
#import <AFNetworking/AFNetworking.h>
#import <MJExtension/MJExtension.h>
#import <SVProgressHUD.h>



@interface CCSubTagController ()

@property (nonatomic, strong) NSArray *items;

@property (nonatomic, weak) AFHTTPSessionManager *mgr;

@end

@implementation CCSubTagController

static NSString  *const cellId = @"subTagCell";

#pragma mark - lazy loading

- (NSArray *)items {
    if (_items == nil) {
        _items = [NSArray array];
    }
    return _items;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadData];
    
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"CCSubTagCell" bundle:nil] forCellReuseIdentifier:cellId];
    
    self.title = @"推荐关注";
    
    
    [SVProgressHUD showWithStatus:@"正在加载..."];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    //消除弹窗
    [SVProgressHUD dismiss];
    //取消当先的请求任务
    [self.mgr.tasks makeObjectsPerformSelector:@selector(cancel)];
    
}

#pragma mark - 请求数据

- (void)loadData {
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    _mgr = mgr;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    //a action c
    parameters[@"a"] = @"tag_recommend";
    parameters[@"c"] = @"topic";
    parameters[@"action"] = @"sub";
    
    [mgr GET:@"http://api.budejie.com/api/api_open.php" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSArray *responseObject) {
        [SVProgressHUD dismiss];
        
        NSArray *itemArr = [CCSubTagItem mj_objectArrayWithKeyValuesArray:responseObject];
        _items = itemArr;
        
//        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
    
    [self.tableView reloadData];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    
    return self.items.count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CCSubTagCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    CCSubTagItem *item = self.items[indexPath.row];
    cell.item = item;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}


@end
